package com.th.cash.th2.product

import android.annotation.SuppressLint
import android.app.Activity.RESULT_OK
import android.content.Intent
import android.database.Cursor
import android.provider.ContactsContract
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.RelativeLayout
import androidx.core.content.ContextCompat
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import com.th.basemodel.base.BaseViewModel
import com.th.basemodel.ext.bindData
import com.th.basemodel.ext.divider
import com.th.basemodel.ext.dp2px
import com.th.basemodel.ext.vertical
import com.th.resmodel.R
import com.th.resmodel.databinding.FragmentContactBinding
import kotlinx.coroutines.launch

class ContactFragment : VerifyBaseFragment<FragmentContactBinding>() {

    override var type = 2

    private val mViewModel by viewModels<ProductVm>()

    val mTempList = mutableListOf<VerifyItemResponse>()

    override fun startObserve() {
        lifecycleScope.launch {
            mViewModel.uiState.collect {
                when (it) {
                    is ProductState.Idle -> {

                    }

                    is ProductState.ContactInfoData -> {
                        mDataList.clear()
                        mTempList.clear()

                        if (it.data.bWBkvxsExtraversionIumEFga.QylNBLMBombitaFwSlPhN.isNotEmpty()) {
                            mDataList.addAll(it.data.bWBkvxsExtraversionIumEFga.QylNBLMBombitaFwSlPhN)

                            mTempList.addAll(mDataList.subList(0,3))
                        }

                        mBinding.rvFillContactList.adapter?.notifyDataSetChanged()
                    }

                    is ProductState.VerifySuccess -> {
                        nextPage(it.data.FqLBwdpDollarbirdSXQntyj.noneconomicSingle)
                    }

                    else -> {}
                }
            }
        }
    }

    override fun init() {
        mBinding.header.headTitle.text = "ติดต่อฉุกเฉิน"

        initContactAdapter(mBinding.rvFillContactList)
        initClick()

        mViewModel.intentChannel.trySend(ProductIntent.InitContactInfo(ContactInfoRequest(getPid())))
    }

    override fun onLazyInitData() {

    }

    private fun initClick() {
        mBinding.header.headBack.setOnClickListener {
            back(2)
        }

        mBinding.tvFillContactSubmit.setOnClickListener {

            val params = mutableListOf<Pair<Triple<String,String,String>,Triple<String,String,String>>>()

            mTempList.forEach {
                params.add(
                    Pair(
                        Triple(it.RAEdwRPQuaveringlyMOIghzQ.gSMjxTNTapsterOCQsMOO,it.RAEdwRPQuaveringlyMOIghzQ.ABOVzAbInsectivizationBIIAYez,it.RAEdwRPQuaveringlyMOIghzQ.oyaUZybReascendHYtTBDd),
                        Triple(it.PxGEecSAntiwarMrDXISc.pTDihliBumpkinOyWuDKA,it.PxGEecSAntiwarMrDXISc.oOJcbnLEffuseTaiOLOz,it.PxGEecSAntiwarMrDXISc.TnLNYShCockleDaANaRv),
                    )
                )
            }

            mViewModel.intentChannel.trySend(
                ProductIntent.SaveContactInfo(
                    ContactSaveRequest(
                        getPid(),
                        params
                    )
                )
            )
        }

        mBinding.ivAddContact.setOnClickListener {
            if (mTempList.size < mDataList.size) {
                mTempList.add(mDataList[mTempList.size])
                mBinding.rvFillContactList.adapter?.notifyDataSetChanged()
            }

            if (mTempList.size == mDataList.size) {
                mBinding.ivAddContact.visibility = View.GONE
            }
        }
    }

    override fun getVm(): BaseViewModel {
        return mViewModel
    }

    companion object {
        fun newInstance(): ContactFragment {
            return ContactFragment()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK && requestCode == 1002) {
            getUserNameAndPhone(data)
        }

    }

    @SuppressLint("Recycle", "Range")
    private fun getUserNameAndPhone(data: Intent?) {
        val uri = data?.data
        uri?.let {
            val queryFields = arrayOf("data1", "display_name")
            val cursor: Cursor? =
                requireContext().contentResolver.query(it, queryFields, null, null, null)
            if (cursor != null && cursor.count > 0) {
                cursor.moveToFirst()

                mSelectItem?.PxGEecSAntiwarMrDXISc?.pTDihliBumpkinOyWuDKA = cursor.getString(1)
                mSelectItem?.PxGEecSAntiwarMrDXISc?.oOJcbnLEffuseTaiOLOz = cursor.getString(0)

                mBinding.rvFillContactList.adapter?.notifyItemChanged(mTempList.indexOf(mSelectItem))

                cursor.close()
            }
        }
    }

    private fun initContactAdapter(recyclerView: RecyclerView) {
        recyclerView.vertical()
            .divider(
                color = ContextCompat.getColor(requireContext(), R.color.white),
                size = dp2px(10f)
            )
            .bindData(mTempList, R.layout.item_fill_contact) { holder, item, position ->

                holder.setText(R.id.tvContactTitle, item.fOEJfxDMilchSvtaQHn)

                // 如果是选择类型，查找匹配的选项
                val selectedValue = item.PxGEecSAntiwarMrDXISc.TnLNYShCockleDaANaRv
                val matchedOption = item.hrbuvGdRemiseQqQMBqZ.find { option ->
                    option.wQFohwTEnormityOlsvnWX == selectedValue
                }

                // 显示匹配的选项文本或默认文本
                val displayText =
                    matchedOption?.LOtUxphBluesmanCElYqFg ?: item.ODymYqTSuperwaterAVPVdvk
                holder.setText(R.id.tvContactRelation, displayText)

                val etFillContact5 = holder.getView<EditText>(R.id.etFillContact5)
                val etFillContact7 = holder.getView<EditText>(R.id.etFillContact7)

                etFillContact5.setText(item.PxGEecSAntiwarMrDXISc.pTDihliBumpkinOyWuDKA)
                etFillContact7.setText(item.PxGEecSAntiwarMrDXISc.oOJcbnLEffuseTaiOLOz)

                val textWatcher1 = object : TextWatcher {
                    override fun beforeTextChanged(
                        s: CharSequence,
                        start: Int,
                        count: Int,
                        after: Int
                    ) {
                    }

                    override fun onTextChanged(
                        s: CharSequence,
                        start: Int,
                        before: Int,
                        count: Int
                    ) {
                    }

                    override fun afterTextChanged(s: Editable) {
                        if (TextUtils.isEmpty(s.toString())) {
                            item.PxGEecSAntiwarMrDXISc.pTDihliBumpkinOyWuDKA = ""
                        } else {
                            item.PxGEecSAntiwarMrDXISc.pTDihliBumpkinOyWuDKA = s.toString()
                        }
                    }
                }

                etFillContact5.onFocusChangeListener = View.OnFocusChangeListener { v, hasFocus ->
                    if (hasFocus) {
                        etFillContact5.addTextChangedListener(textWatcher1)
                    } else {
                        etFillContact5.removeTextChangedListener(textWatcher1)
                    }
                }

                val textWatcher2 = object : TextWatcher {
                    override fun beforeTextChanged(
                        s: CharSequence,
                        start: Int,
                        count: Int,
                        after: Int
                    ) {
                    }

                    override fun onTextChanged(
                        s: CharSequence,
                        start: Int,
                        before: Int,
                        count: Int
                    ) {
                    }

                    override fun afterTextChanged(s: Editable) {
                        if (TextUtils.isEmpty(s.toString())) {
                            item.PxGEecSAntiwarMrDXISc.oOJcbnLEffuseTaiOLOz = ""
                        } else {
                            item.PxGEecSAntiwarMrDXISc.oOJcbnLEffuseTaiOLOz = s.toString()
                        }
                    }
                }

                etFillContact7.onFocusChangeListener = View.OnFocusChangeListener { v, hasFocus ->
                    if (hasFocus) {
                        etFillContact7.addTextChangedListener(textWatcher2)
                    } else {
                        etFillContact7.removeTextChangedListener(textWatcher2)
                    }
                }

                holder.getView<LinearLayout>(R.id.llFillContact1).setOnClickListener {
                    startSelect(item)
                }

                holder.getView<RelativeLayout>(R.id.rlFillContact3).setOnClickListener {
                    selectItem(mBinding.rvFillContactList, item,false)
                }
            }
    }

    private var mSelectItem: VerifyItemResponse? = null

    private fun startSelect(item: VerifyItemResponse) {
        mSelectItem = item

        val intent = Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI)
        startActivityForResult(intent, 1002)
    }

}